package com.yiding.sys.controller;

import com.yiding.sys.common.model.Result;
import com.yiding.sys.common.enums.ResultCodeEnum;
import com.yiding.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author War horse imwarhorse@aliyun.com
 * Date: 2020/8/7
 * Description: 系统相关Request Handler
 */

@Controller
public class SysController {

	@Autowired
	private SysUserService sysUserService;

	/**
	 * 无权限页面
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("unauthorized")
	public Result unauthorized() {
		return new Result().geneFailed(ResultCodeEnum.UNAUTHORIZED);
	}

	/**
	 * 登录页面
	 *
	 * @return
	 */
	@RequestMapping("/signin")
	public String toLoginPage() {
		return "/login";
	}

	@RequestMapping("/logout")
	public String logout() {
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();

		return "redirect:/signin";
	}

	/**
	 * 返回/page/main页面
	 *
	 * @return
	 */
	@RequestMapping("/page/main")
	public String toMainPage() {
		return "/page/main";
	}

	/**
	 * 用户登录接口
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @return
	 */
	@PostMapping("/sys/login")
	String login(@RequestParam("username") String username,
	             @RequestParam("password") String password) {
		if (sysUserService.login(username, password)) {
			// 登录成功。重定向到管理页面
			return "redirect:/page/main";
		} else {
			return "forward:/signin";
		}
	}
}
